package com.llc.mall.user.application.query.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;
import com.llc.mall.common.core.exception.Mall4cloudException;
import com.llc.mall.common.database.qo.BasePageQo;
import com.llc.mall.common.database.util.PageUtil;
import com.llc.mall.common.database.vo.PageVO;
import com.llc.mall.common.security.AuthUserContext;
import com.llc.mall.user.application.query.service.UserQueryService;
import com.llc.mall.user.infrastructure.persist.mapper.UserMapper;
import com.llc.mall.user.infrastructure.persist.po.UserPo;
import com.llc.mall.user.interfaces.vo.UserVo;
import com.mall4j.cloud.api.auth.bo.UserInfoInTokenBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserQueryServiceImpl implements UserQueryService {

    private final UserMapper userMapper;

    public UserQueryServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserVo detail() {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        if (userInfoInTokenBO == null) {
            throw new Mall4cloudException("当前用户未登录!");
        }
        Long userId = userInfoInTokenBO.getUserId();
        UserPo userPo = userMapper.getByUserId(userId);
        return new UserVo(userId, userPo.getNickName(), userPo.getPic(), userPo.getStatus(), userPo.getCreateTime(), userPo.getUpdateTime(), Lists.newArrayList());
    }

    @Override
    public PageVO<UserVo> page(BasePageQo basePageQo) {
        PageVO<UserPo> pageVO = PageUtil.doPage(basePageQo, userMapper::list);
        List<UserPo> list = pageVO.getList();
        List<UserVo> userVoList = BeanUtil.copyToList(list, UserVo.class);
        PageVO<UserVo> resultPageVO = new PageVO<>();
        resultPageVO.setTotal(pageVO.getTotal());
        resultPageVO.setList(userVoList);
        return resultPageVO;
    }
}
